
#include "backup.hpp"
#include <iostream>

inline bool need_new_stat( time_t now, time_t last_span ) { return ( (now/3600)*3600 - last_span ) >= 3600; }

std::string make_file_name( time_t now, const std::string& format)
{
  char name[256];
  time_t now_h = (now/3600)*3600;
  sprintf(name, format.c_str(), static_cast<const int&>(now_h) );
  return name;
}

backup::~backup()
{
}


backup::backup()
  : _last(0)
{
}

void backup::initialize(const std::string& path_format)
{
  _path_format = path_format;
}

void backup::flush()
{
  if (_file)
    _file.flush();
}

void backup::write(time_t now, const char* d, size_t s)
{
  _check_file(now);
  if (_file)
    _file.write(d, s);
}

void backup::write( const char* d, size_t s)
{
  this->write( time(0), d, s);
}

bool backup::read(time_t now, int hour_ago, std::vector<char>& data)
{
  data.clear();
  std::string filename = make_file_name(now - hour_ago*3600, _path_format);
  std::ifstream f(filename.c_str(), std::ios_base::binary);
  
  if (!f) 
  {
    std::cout << "not_found: " << filename << std::endl;
    return false;
  }
  std::copy(
    std::istreambuf_iterator<char>(f),
    std::istreambuf_iterator<char>(),
    std::back_inserter(data)
  );

  return true;
}


void backup::_check_file(time_t now)
{
  if ( need_new_stat(now, _last) || !_file)
  {
    if (_file) _file.close();
    std::string filename = make_file_name(now, _path_format);
    _file.open( filename.c_str(), std::ios_base::app | std::ios_base::binary);
    if ( _file )
      _last = (now/3600)*3600;
    else
      std::cout << "open fail!" <<std::endl;
  }
}
